package org.luxor.schedule.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.luxor.commons.core.utils.BeanUtils;
import org.luxor.commons.jdbc.annotation.DS;
import org.luxor.commons.schedule.constant.ScheduleStatus;
import org.luxor.commons.schedule.entity.ScheduleJobEntity;
import org.luxor.commons.schedule.service.IScheduleJobService;
import org.luxor.commons.schedule.utils.ScheduleUtils;
import org.luxor.schedule.mapper.ScheduleJobMapper;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 定时任务
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.2.0 2016-11-28
 */
@Service("scheduleJobService")
@DS("${spring.quartz.dataSource:master}")
public class ScheduleJobServiceImpl extends ServiceImpl<ScheduleJobMapper, ScheduleJobEntity> implements IScheduleJobService {

    @Resource
    private Scheduler scheduler;

    @Override
    public IPage<ScheduleJobEntity> page(IPage<ScheduleJobEntity> page, Map search) {
        ScheduleJobEntity query = BeanUtils.toObject(ScheduleJobEntity.class, search);
        return super.page(page, Wrappers.query(query));
    }

    @Override
    public Long getLogId(String beanName, String methodName) {
        Wrapper<ScheduleJobEntity> wrapperQuery = Wrappers.<ScheduleJobEntity>lambdaUpdate()
                .eq(ScheduleJobEntity::getBeanName, beanName)
                .eq(ScheduleJobEntity::getMethodName, methodName);
        return this.getOne(wrapperQuery, true).getId();
    }

    /**
     * 项目启动时，初始化定时器
     */
    @PostConstruct
    public void init() {
        List<ScheduleJobEntity> scheduleJobList = this.list();
        for (ScheduleJobEntity scheduleJob : scheduleJobList) {
            CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler, scheduleJob.getId());
            //如果不存在，则创建
            if (cronTrigger == null) {
                ScheduleUtils.createScheduleJob(scheduler, scheduleJob);
            } else {
                ScheduleUtils.updateScheduleJob(scheduler, scheduleJob);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveJob(ScheduleJobEntity scheduleJob) {
        scheduleJob.setCreateTime(new Date());
        scheduleJob.setStatus(ScheduleStatus.NORMAL.getValue());
        this.saveOrUpdate(scheduleJob);
        ScheduleUtils.createScheduleJob(scheduler, scheduleJob);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ScheduleJobEntity scheduleJob) {
        Wrapper<ScheduleJobEntity> wrapperUpdate = Wrappers.<ScheduleJobEntity>lambdaUpdate()
                .eq(ScheduleJobEntity::getId, scheduleJob.getId());
        this.update(scheduleJob, wrapperUpdate);
        ScheduleUtils.updateScheduleJob(scheduler, scheduleJob);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(List<Long> jobIds) {
        for (Long jobId : jobIds) {
            ScheduleUtils.deleteScheduleJob(scheduler, jobId);
        }
        this.removeByIds(jobIds);
    }

    @Override
    public int updateBatch(List<Long> jobIds, int status) {
        Map<String, Object> map = new HashMap<>(2);
        map.put("list", jobIds);
        map.put("status", status);
        return baseMapper.updateBatch(map);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void run(List<Long> jobIds) {
        for (Long jobId : jobIds) {
            ScheduleUtils.run(scheduler, this.getById(jobId));
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void pause(List<Long> jobIds) {
        for (Long jobId : jobIds) {
            ScheduleUtils.pauseJob(scheduler, jobId);
        }
        updateBatch(jobIds, ScheduleStatus.PAUSE.getValue());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resume(List<Long> jobIds) {
        for (Long jobId : jobIds) {
            ScheduleUtils.resumeJob(scheduler, jobId);
        }
        updateBatch(jobIds, ScheduleStatus.NORMAL.getValue());
    }

}
